<?php

namespace app\widgets;

use app\models\Categories;
use yii\helpers\Url;
use yii\widgets\Menu;
use yii;

class AppMenu extends Menu {

    public $encodeLabels = FALSE;
    public $activeCssClass = 'active';
    public $options = ['class' => 'menu menu-horizontal', 'id' => 'menu'];
    public $itemOptions = ['class' => 'menu-item'];
    public $submenuTemplate = "\n<ul class=\"sub-menu\">\n{items}\n</ul>\n";


    public function init() {
        parent::init();
        $this->route = str_replace('index', '', Yii::$app->controller->uniqueId);

        $this->items = [
            ['label' => '首页', 'url' => ['/']],
        ];
        $this->initItems();
    }


    protected function initItems() {
        $items = Categories::find()->where(['type' => Categories::TYPE_VIDEO])->andWhere(['>', 'parent_id', 0])->asArray()->orderBy('sort asc')->all();

        $items_more = array_slice($items, 4);

        $items = array_slice($items, 0, 4);
        foreach ($items as $k => $item) {
            $this->items[] = [
                'label' => $item['title'],
                'url' => ['category/', 'slug' => $item['slug']]
            ];
        }

        $item_more = [
            'label' => '更多',
            'url' => 'javascript:;',
            'items' => []
        ];
        foreach ($items_more as $k => $item) {
            $item_more['items'][] = [
                'label' => $item['title'],
                'url' => ['category/', 'slug' => $item['slug']]
            ];
        }
        $this->items[] = $item_more;
    }

    protected function isItemActive($item) {
        if (isset($item['url']) && is_array($item['url']) && isset($item['url'][0])) {
            $route = Yii::getAlias($item['url'][0]);
            if ($route[0] !== '/' && Yii::$app->id) {
                $route = Yii::$app->controller->module->getUniqueId() . '/' . $route;
            }

            if (isset($item['url']['slug'])) {
                $slug = strtolower(Yii::$app->request->get('slug'));
                if ($item['url']['slug'] == $slug) {
                    return TRUE;
                }
            } else {
                if (trim($route, '/') === $this->route) {
                    print_r([$route, $this->route]);
                    return TRUE;
                }
                if (trim($route, '/') === trim(Yii::$app->request->url, '/')) {
                    return TRUE;
                }
            }

            //print_r([$route, Yii::$app->request->url, $this->route]);

            unset($item['url']['#']);
            if (count($item['url']) > 1) {
                $params = $item['url'];
                unset($params[0]);
                foreach ($params as $name => $value) {
                    if ($value !== NULL && (!isset($this->params[$name]) || $this->params[$name] != $value)) {
                        return FALSE;
                    }
                }
            }
            return FALSE;
        }
        return FALSE;
    }
}